package com.itheima.tanhua.autoconfig.template;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.tanhua.autoconfig.properties.OssProperties;
import com.sun.org.apache.bcel.internal.generic.NEW;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author Lff
 * @date 2022/3/23
 */
public class OssTemplate {
    private OssProperties ossProperties;

    private OssTemplate() {
    }

    public OssTemplate(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    /**
     * 文件上传
     * 参数1：文件名(需要后缀)
     * 参数2：输入流
     */
    public String upload(String name, InputStream is) {
        //构建新的文件地址
        String objectName = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + UUID.randomUUID() + name.substring(name.lastIndexOf("."));
        //构建一个OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
                ossProperties.getAccessKey(), ossProperties.getSecret());
        //文件上传
        ossClient.putObject(ossProperties.getBucketName(), objectName, is);
        //关闭资源
        ossClient.shutdown();
        //返回文件的网络地址
        return ossProperties.getUrl() + objectName;
    }

    /**
     * 文件删除
     */
    public String delete(String url) {
        //构建新的文件地址
        //
        String objectName = url.substring(50);
        //构建一个OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
                ossProperties.getAccessKey(), ossProperties.getSecret());
        //文件上传
        ossClient.deleteObject(ossProperties.getBucketName(), objectName);
        //关闭资源
        ossClient.shutdown();
        //返回文件的网络地址
        return ossProperties.getUrl() + objectName;
    }


}
